import { addRoleApi, delRoleApi, editRoleApi } from '@/api/system/role/role'
import { AddRoleModel, RoleParam, RoleModel } from '@/api/system/role/RoleModel'
import useInstance from '@/hooks/useInstance'
import { Result, StatusCode } from '@/http/request'
import { EditType } from '@/types/BaseEnum'
import { reactive, ref } from 'vue'

export default function useRole(getRoleList: any) {
    const { global } = useInstance()

    // 新增弹框ref属性
    const addEditRef = ref<{
        show: (type: string, row?: RoleModel) => void
    }>()
    // const addDeptRef = ref<InstanceType<typeof AddAndEdit>>() // 打包时会报错

    // 分配角色弹框ref属性
    const assignMenuRef = ref<{
        show: (name: string, roleId: string | number) => void
    }>()

    const addModel = reactive<RoleModel>({
        id: 0,
        role_name: '',
        remark: '',
        type: '',
        status: '1'
    })

    // 新增
    const addBtn = () => {
        addModel.status = '1'
        addEditRef.value?.show(EditType.ADD, addModel)
    }

    // 编辑
    const editBtn = async (row: RoleModel) => {
        row.status = String(row.status)
        addEditRef.value?.show(EditType.EDIT, row)
    }

    // 删除
    const delBtn = async (id: number) => {
        console.log(global)
        const confirm = await global.$eleConfirm('确定删除该数据吗？')
        if (confirm) {
            // 执行删除操作
            const param = reactive<RoleParam>({
                id: id
            })
            let res = await delRoleApi(param)
            if (res && res.code == StatusCode.Success) {
                // 刷新列表
                getRoleList()
                // 信息提示
                global.$message({ message: res.msg, type: 'success' })
            }
        }
    }

    // 保存
    const save = async (param: RoleModel) => {
        const roleParam = reactive<AddRoleModel>({
            id: param.id,
            role_name: param.role_name,
            type: param.type,
            remark: param.remark,
            status: parseInt(param.status)
        })
        console.log('保存：', roleParam)
        let res: Result
        if (roleParam.type == EditType.ADD) {
            res = await addRoleApi(roleParam)
        } else {
            res = await editRoleApi(roleParam)
        }
        if (res && res.code == StatusCode.Success) {
            // 信息提示
            global.$message({ message: res.msg, type: 'success' })
            // 刷新表格
            getRoleList()
        }
    }
    // 分配权限
    const assignBtn = (name: string, roleId: string | number) => {
        // 显示弹框
        assignMenuRef.value?.show(name, roleId)
    }
    return {
        addBtn,
        editBtn,
        delBtn,
        save,
        addEditRef,
        assignMenuRef,
        assignBtn
    }
}
